package top.codecrab.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author codecrab
 * @since 2021年05月17日 9:23
 */
@Component
public class MyLb implements LoadBalancer {

    private final AtomicInteger nextServerCyclicCounter = new AtomicInteger(0);

    public final int getNextAndIncrement() {
        int current, next;

        do {
            current = this.nextServerCyclicCounter.get();
            next = current >= Integer.MAX_VALUE ? 0 : current + 1;
        } while (!this.nextServerCyclicCounter.compareAndSet(current, next));

        System.out.println("第 " + next + " 次调用");
        return next;
    }

    @Override
    public ServiceInstance instance(List<ServiceInstance> instances) {
        int index = this.getNextAndIncrement() % instances.size();
        return instances.get(index);
    }
}
